﻿using System;
using eCommerce.BusinessLogic;
using eCommerce.DataAccess;

namespace eCommerce.Site.Controls
{
    public partial class Newsletter : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Gets the subsriber.
        /// </summary>
        /// <param name="userEmail">The user email.</param>
        /// <param name="userName">Name of the user.</param>
        public void GetSubsriber(string userEmail, string userName)
        {
            using (WebsiteDataContext ds = new WebsiteDataContext())
            {
                // Check if email address exists
                NewsletterBL newsletterBL = new NewsletterBL();
                Xcms_Subscriber subscriber = newsletterBL.GetSubscriber(userEmail, userName);
                if (subscriber == null)
                {
                    // Add Email address to database
                    Xcms_Subscriber subscribers = new Xcms_Subscriber
                                                      {
                                                          name = txbName.Text.Trim(),
                                                          email = txbEmail.Text.Trim(),
                                                          datesubscribed =
                                                              Convert.ToDateTime(DateTime.Now.ToShortDateString()),
                                                          status = "true"
                                                      };
                    ds.Xcms_Subscribers.InsertOnSubmit(subscribers);
                    ds.SubmitChanges();
                    // Send Confirmation Emails to Client and Admin
                    newsletterBL.SendEmailReply(txbEmail.Text.Trim(), "info@example.com", "Example Newsletter Subscription", txbName.Text.Trim(), "devsite.2beknown.co.uk", "Example eCommerce Company");
                   

                }
                else
                {
                    txbName.Text = "You are already Subscribed";
                    txbEmail.Text = "to our Newsletter!";
                }
            }
        }

        protected void lnkbtnAdd_Click(object sender, EventArgs e)
        {

            try
            {
                GetSubsriber(txbEmail.Text.Trim(), txbName.Text.Trim());
                txbName.Text = "Thank you for Subscribing";
                txbEmail.Text = "to our Newsletter!";
            }
            catch (Exception ex)
            {
                NewsletterBL newsletterBL = new NewsletterBL();
                newsletterBL.SendTechError("devsite.2beknown.co.uk", "Example eCommerce - Newsletter Subscription", txbEmail.Text.Trim(), ex.Message, ex.StackTrace, ex.TargetSite);
                txbName.Text = "An Error has occured!";
                txbEmail.Text = "";
            }

        }

    }
}         
